// pages/order/order.js
import showValidateModal from "../../utils/showValidateModal";
import utils from "../../utils/util";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  orderDetail(e) {
    const _id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `../orderDetail/orderDetail?id=${_id}` });
  },
  data: {
    tabList: ["全部", "我的订单", "我帮助的", "正在悬赏"],
    currentTab: 0,
    orderAll: [], //所有订单
    orderMy: [], //我的订单
    orderHelp: [], //我帮助的
    orderUnHelp: [], //正在悬赏
    page: 0, //分页，默认0 即为第一页
    totalCount: 0, //订单数
    pageSizes: 5, //每页显示5条记录
    haveData: true, //数据库中存在记录
    helpedOrders: 0, //已帮助的单数量
    earnMoney: 0, //已赚钱金额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    //页面加载时，清空订单
    this.setData({ page: 0, orderAll: [] });
    //读取订单数量
    await this.getTotalCount();
    //console.log(this.data.totalCount)
    //读取所有订单
    await this.getOrderList();
  },
  //获取数据库记录数
  getTotalCount() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.server}/orderCount`,
        success: (res) => {
          this.setData({ totalCount: res.data.count });
          resolve({ status: "ok" });
        },
        fail: (err) => {
          reject({ status: err });
        },
      });
    });
  },
  //获取订单
  getOrderList() {
    return new Promise((resolve, reject) => {
      const { orderAll, page, pageSizes, totalCount } = this.data;
      //orderAll.length为已取得的数据记录数，>=totalCount 说明已取完所有数据或不存在数 据
      if (orderAll.length >= totalCount) {
        this.setData({ haveData: false });
        resolve("nodata");
        return;
      }
      wx.showLoading({ title: "加载中" });
      wx.request({
        url: `${app.globalData.server}/orderList`,
        data: { page: page * pageSizes, pageSizes },
        success: (res) => {
          if (res.data.length > 0) {
            const { orderAll } = this.data;
            //将订单内容格式化输出
            const newOrderArray = this.formatOrderContent(res.data);
            this.setData({ orderAll: orderAll.concat(newOrderArray) });
            //console.log(this.data.orderAll)
            wx.hideLoading();
            resolve({ status: "ok" });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          console.log(err);
          reject(err);
        },
      });
    });
  },
  //格式化订单列表内容
  formatOrderContent(order) {
    return order.map((item) => {
      switch (item.orderType) {
        case "快递代取":
          var {
            _id,
            orderType,
            startAddress,
            endAddress,
            payMoney,
            publicTime,
            status,
            userInfo,
            completed,
            isCompleted,
            commentList,
          } = item;
          var content = `快件大小：${item.info.expressType}--快递数量： ${item.info.expressNum}--备注：${item.info.mark}--期望送达： ${item.info.arriveTime}--${item.info.genderLimit}`;
          var newItem = {
            _id,
            orderType,
            startAddress,
            endAddress,
            payMoney,
            publicTime,
            status,
            completed,
            isCompleted,
            userInfo,
            content,
            commentList,
            dateDif: this.timeDiff(item.publicTime),
          };
          return newItem;
          break;
        case "打印服务":
          var {
            _id,
            orderType,
            endAddress,
            payMoney,
            completed,
            isCompleted,
            publicTime,
            status,
            userInfo,
            commentList,
          } = item;
          var content = `页数：${item.info.pageNum}--备注：${item.info.mark}- -${item.info.colorPrint}--${item.info.doublePrint}`;
          var newItem = {
            _id,
            orderType,
            endAddress,
            payMoney,
            publicTime,
            status,
            content,
            completed,
            isCompleted,
            userInfo,
            commentList,
            dateDif: this.timeDiff(item.publicTime),
          };
          return newItem;
          break;
        case "校园跑腿":
          return Object.assign(
            {},
            item,
            { content: item.info.content },
            { dateDif: this.timeDiff(item.publicTime) }
          );
          break;
        case "快递代寄":
          var {
            _id,
            orderType,
            startAddress,
            endAddress,
            completed,
            isCompleted,
            payMoney,
            publicTime,
            status,
            userInfo,
            commentList,
          } = item;
          var content = `${item.info.expressInfo}--备注：${item.info.mark}`;
          var newItem = {
            _id,
            orderType,
            startAddress,
            endAddress,
            payMoney,
            publicTime,
            status,
            completed,
            isCompleted,
            userInfo,
            content,
            commentList,
            dateDif: this.timeDiff(item.publicTime),
          };
          return newItem;
          break;
        case "租借服务":
          var {
            _id,
            orderType,
            startAddress,
            endAddress,
            completed,
            isCompleted,
            payMoney,
            publicTime,
            status,
            userInfo,
            commentList,
          } = item;
          var content = `${item.info.content}--租借时长： ${item.info.rentDuration}--预计交货时间：${item.info.deliveryTime}`;
          var newItem = {
            _id,
            orderType,
            startAddress,
            endAddress,
            payMoney,
            publicTime,
            status,
            userInfo,
            completed,
            isCompleted,
            content,
            commentList,
            dateDif: this.timeDiff(item.publicTime),
          };
          return newItem;
          break;
        case "游戏陪玩":
          var {
            _id,
            orderType,
            payMoney,
            publicTime,
            completed,
            isCompleted,
            status,
            userInfo,
            commentList,
          } = item;
          var content = `游戏平台：${item.info.platform}--游戏时间或盘数： ${item.info.playDuration}--备注：${item.info.mark}--游戏ID：${item.info.gameID}`;
          var newItem = {
            _id,
            orderType,
            payMoney,
            publicTime,
            status,
            userInfo,
            content,
            completed,
            isCompleted,
            commentList,
            dateDif: this.timeDiff(item.publicTime),
          };
          return newItem;
          break;
        case "代扔垃圾":
          var {
            _id,
            orderType,
            startAddress,
            endAddress,
            payMoney,
            publicTime,
            status,
            completed,
            isCompleted,
            userInfo,
            commentList,
          } = item;
          var content = `垃圾大小：${item.info.rubbishType}--垃圾数量： ${item.info.rubbishNum}--备注：${item.info.mark}`;
          var newItem = {
            _id,
            orderType,
            startAddress,
            endAddress,
            completed,
            isCompleted,
            payMoney,
            publicTime,
            status,
            userInfo,
            commentList,
            content,
            dateDif: this.timeDiff(item.publicTime),
          };
          return newItem;
          break;
        case "代替服务":
          return Object.assign(
            {},
            item,
            { content: item.info.content },
            { dateDif: this.timeDiff(item.publicTime) }
          );
          break;
        case "其他帮助":
          return Object.assign(
            {},
            item,
            { content: item.info.content },
            { dateDif: this.timeDiff(item.publicTime) }
          );
          break;
      }
    });
  },
  //计算时间差
  timeDiff(timeStr) {
    let result = 0;
    const date1 = new Date(timeStr).getTime();
    const date2 = Date.now();
    const date3 = date2 - date1; //剩余天数
    const days = Math.floor(date3 / (24 * 3600 * 1000)); //剩余小时数
    const leave = date3 % (24 * 3600 * 1000); //扣除天数后剩余的毫秒数
    const hours = Math.floor(leave / (3600 * 1000)); //剩余分钟数
    const level2 = leave % (3600 * 1000); //扣除小时数后剩余的毫秒数
    const minutes = Math.floor(level2 / (60 * 1000)); //剩余秒数
    const leave3 = level2 % (60 * 1000); //扣除分钟数后剩余的毫秒数
    const seconds = Math.floor(leave3 / 1000);
    if (days > 0) {
      result = `${days}天前`;
    } else if (hours > 0) {
      result = `${hours}小时前`;
    } else if (minutes > 0) {
      result = `${minutes}分前`;
    } else if (seconds > 0) {
      result = `${seconds}秒前`;
    } else {
      result = "刚发布";
    }
    return result;
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    wx.showLoading();
    //刷新时需要先清空数据
    this.setData({
      page: 0,
      orderAll: [],
      orderMy: [],
      orderHelp: [],
      orderUnHelp: [],
      haveData: true,
    });
    switch (this.data.currentTab) {
      case 0: //全部订单 //console.log(this.data.page)
        await this.getOrderList();
        break;
      case 1: //我的订单
        await this.getMyOrder();
        break;
      case 2: //我帮助的
        await this.getHelpOrder();
        break;
      case 3: //正在悬赏
        await this.getUnHelpOrder();
        break;
    }
    wx.hideLoading();
    wx.stopPullDownRefresh(); //停止刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  async onReachBottom() {
    //页数+1，即取下一页
    this.data.page += 1;
    switch (this.data.currentTab) {
      case 0: //全部订单 //console.log(this.data.page)
        await this.getOrderList();
        break;
      case 1: //我的订单
        await this.getMyOrder();
        break;
      case 2: //我帮助的
        await this.getHelpOrder();
        break;
      case 3: //正在悬赏
        await this.getUnHelpOrder();
        break;
    }
  },
  //点击接单
  async acceptOrder(e) {
    const { id } = e.currentTarget.dataset;
    console.log(id); //判断用户是否登录
    const r = await showValidateModal.cklogin(app.globalData.userInfo);
    if (!r) {
      return false;
    }
    // 判断用户是否绑定手机号
    if (wx.getStorageSync("userInfo").phone === "") {
      wx.showToast({
        title: "请先绑定手机号",
        icon: "error",
        success() {
          setTimeout(() => {
            wx.navigateTo({
              url: "/pages/user/personInfo/personInfo",
            });
          }, 500);
        },
      });
      return;
    }
    //判断当前用户是否已申请接单权限
    if (!app.globalData.userInfo.canReceive) {
      wx.showToast({ title: "您尚未开通接单权限", icon: "error" });
      return false;
    }
    wx.showModal({
      title: "接单确认",
      content: "您确认要接此订单么？",
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: `${app.globalData.server}/updateOrder`,
            method: "POST",
            data: {
              id,
              acceptMan: app.globalData.userInfo.openid,
              acceptTime: utils.formatTime(new Date()),
              status: "已帮助",
              completed: "未完成",
              isCompleted: true,
            },
            success: (res) => {
              wx.navigateTo({ url: "/pages/orderDetail/orderDetail?id=" + id });
            },
          });
        }
      },
    });
  },
  //获取我的订单数据库记录数
  getMyTotalCount() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.server}/orderCount`,
        data: { openid: app.globalData.userInfo.openid },
        success: (res) => {
          this.setData({ totalCount: res.data.count });
          resolve({ status: "ok" });
        },
        fail: (err) => {
          reject({ status: e });
        },
      });
    });
  },
  //我的订单
  getMyOrder() {
    return new Promise((resolve, reject) => {
      const { orderMy, page, pageSizes, totalCount } = this.data;
      if (orderMy.length >= totalCount) {
        //已取出全部记录
        this.setData({ haveData: false });
        resolve("nodata");
        return;
      }
      wx.showLoading({ title: "加载中" });
      wx.request({
        url: `${app.globalData.server}/orderList`,
        data: {
          page: page * pageSizes,
          pageSizes,
          openid: app.globalData.userInfo.openid,
        },
        success: (res) => {
          if (res.data.length > 0) {
            const { orderMy } = this.data; //将订单内容格式化输出
            const newOrderArray = this.formatOrderContent(res.data);
            this.setData({ orderMy: orderMy.concat(newOrderArray) });
            wx.hideLoading();
            resolve({ status: "ok" });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          console.log(err);
          reject(err);
        },
      });
    });
  },
  //标签导航
  async tabChange(e) {
    this.setData({ currentTab: e.detail, haveData: true });
    switch (e.detail) {
      case 0: //所有订单
        this.onShow();
        break;
      case 1: //我的订单
        this.setData({ page: 0, orderMy: [] });
        await this.getMyTotalCount();
        await this.getMyOrder();
        break;
      case 2: //我帮助的
        this.setData({ page: 0, orderHelp: [] });
        await this.helpedOrders();
        await this.getHelpTotalCount();
        await this.getHelpOrder();
        break;
      case 3: //正在悬赏
        this.setData({ page: 0, orderUnHelp: [] });
        await this.getUnHelpTotalCount();
        await this.getUnHelpOrder();
        break;
    }
  },
  //删除订单
  delOrder(e) {
    console.log(e.currentTarget.dataset);
    const { id, index } = e.currentTarget.dataset;
    wx.showModal({
      title: "提示",
      content: "您确认删除当前订单么？",
      success: (res) => {
        if (res.confirm) {
          //点击确认操作
          wx.showLoading();
          wx.request({
            url: `${app.globalData.server}/delOrder/${id}`,
            success: (res) => {
              if (res.data == "success") {
                //从orderMy数组中删除对应下标数据
                let orderMy = this.data.orderMy;
                orderMy.splice(index, 1);
                this.setData({ orderMy });
                wx.showToast({ title: "删除成功", icon: "success" });
              } else {
                wx.hideLoading({});
                wx.showToast({ title: "删除失败", icon: "error" });
              }
            },
            fail: (err) => {
              console.log(err);
              wx.hideLoading({});
              wx.showToast({ title: "删除失败", icon: "error" });
            },
            complete: () => {
              wx.hideLoading({});
            },
          });
        }
      },
    });
  },
  //我帮助的订单统计
  helpedOrders() {
    // console.log(2);
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.server}/helpedOrders`,
        data: {
          acceptMan: app.globalData.userInfo.openid,
          completed: "已完成",
        },
        success: (res) => {
          // console.log(res.data.total);
          if (res.data.total.length > 0) {
            // console.log(res.data.total[0].orderCounts);
            this.setData({
              helpedOrders: res.data.total[0].orderCounts,
              earnMoney: res.data.total[0].earnMoney,
            });
          }
          resolve({ status: "ok" });
        },
        fail: (err) => {
          reject({ status: e });
        },
      });
    });
  },
  //获取我帮助的订单数据库记录数
  getHelpTotalCount() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.server}/orderCount`,
        data: {
          acceptMan: app.globalData.userInfo.openid,
          completed: "已完成",
        },
        success: (res) => {
          // console.log(res);
          this.setData({ totalCount: res.data.count });
          resolve({ status: "ok" });
        },
        fail: (err) => {
          reject({ status: e });
        },
      });
    });
  },
  //我帮助的订单
  getHelpOrder() {
    return new Promise((resolve, reject) => {
      const { orderHelp, page, pageSizes, totalCount } = this.data;
      if (orderHelp.length >= totalCount) {
        //已取出全部记录
        this.setData({ haveData: false });
        resolve("nodata");
        return;
      }
      wx.showLoading({ title: "加载中" });
      wx.request({
        url: `${app.globalData.server}/orderList`,
        data: {
          page: page * pageSizes,
          pageSizes,
          acceptMan: app.globalData.userInfo.openid,
          completed: "已完成",
        },
        success: (res) => {
          if (res.data.length > 0) {
            const { orderHelp } = this.data;
            //将订单内容格式化输出
            const newOrderArray = this.formatOrderContent(res.data);
            this.setData({ orderHelp: orderHelp.concat(newOrderArray) });
            wx.hideLoading();
            resolve({ status: "ok" });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          console.log(err);
          reject(err);
        },
      });
    });
  },
  //获取正在悬赏订单数据库记录数
  getUnHelpTotalCount() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.server}/orderCount`,
        data: { status: "待帮助" },
        success: (res) => {
          this.setData({ totalCount: res.data.count });
          resolve({ status: "ok" });
        },
        fail: (err) => {
          reject({ status: e });
        },
      });
    });
  },
  //正在悬赏的订单
  getUnHelpOrder() {
    return new Promise((resolve, reject) => {
      const { orderUnHelp, page, pageSizes, totalCount } = this.data;
      if (orderUnHelp.length >= totalCount) {
        //已取出全部记录
        this.setData({ haveData: false });
        resolve("nodata");
        return;
      }
      wx.showLoading({ title: "加载中" });
      wx.request({
        url: `${app.globalData.server}/orderList`,
        data: { page: page * pageSizes, pageSizes, status: "待帮助" },
        success: (res) => {
          if (res.data.length > 0) {
            const { orderUnHelp } = this.data;
            //将订单内容格式化输出
            const newOrderArray = this.formatOrderContent(res.data);
            this.setData({ orderUnHelp: orderUnHelp.concat(newOrderArray) });
            wx.hideLoading();
            resolve({ status: "ok" });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          console.log(err);
          reject(err);
        },
        complete: () => {
          wx.hideLoading();
        },
      });
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
